﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'dart:ui' as ui;
import 'activity_logic.dart';
import '../../../services/ring_service.dart';

/// 活动页面
/// 显示当前步数、卡路里、时长和环状图
class ActivityView extends GetView<ActivityLogic> {
  const ActivityView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '活动',
                  selectedIndex: _getSelectedIndex(),
                  onTabChanged: (index) {
                    TimeRange timeRange;
                    switch (index) {
                      case 0:
                        timeRange = TimeRange.day;
                        break;
                      case 1:
                        timeRange = TimeRange.week;
                        break;
                      case 2:
                        timeRange = TimeRange.month;
                        break;
                      default:
                        timeRange = TimeRange.day;
                    }
                    controller.setTimeRange(timeRange);
                  },
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.calendar_today,
                          color: Colors.white),
                      onPressed: controller.showCalendarPicker,
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Stack(
                  children: [
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      height: 240.h,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomRight,
                            colors: ThemeManager.to.backgroundGradientColors,
                            stops: const [0.1, 0.3, 0.7, 1.0],
                          ),
                        ),
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.all(16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(height: 20.h),
                          _buildStepsDisplay(),
                          SizedBox(height: 12.h),
                          _buildDateLine(),
                          SizedBox(height: 16.h),
                          _buildStepsChart(),
                          SizedBox(height: 24.h),
                          _buildWeeklyRingView(),
                          SizedBox(height: 20.h),
                          _buildStepsRangeBarChart(),
                          SizedBox(height: 40.h),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取当前选中的索引
  int _getSelectedIndex() {
    switch (controller.currentTimeRange) {
      case TimeRange.day:
        return 0;
      case TimeRange.week:
        return 1;
      case TimeRange.month:
        return 2;
    }
  }



  /// 构建日期行
  Widget _buildDateLine() {
    return Obx(() {
      String dateText;
      
      switch (controller.currentTimeRange) {
        case TimeRange.day:
          // 日视图：显示具体日期和星期
          if (controller.eventInfoRecordDate.isNotEmpty) {
            final weekName = controller.eventInfoWeekName.isNotEmpty 
                ? controller.eventInfoWeekName 
                : '';
            dateText = '${controller.eventInfoRecordDate}，$weekName，00:00 平均';
          } else {
            final now = DateTime.now();
            final weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            final weekday = weekdays[(now.weekday - 1).clamp(0, 6)];
            dateText = '${now.year}年${now.month.toString().padLeft(2, '0')}月${now.day.toString().padLeft(2, '0')}日，$weekday，00:00 平均';
          }
          break;
          
        case TimeRange.week:
          // 周视图：显示日期范围
          if (controller.eventInfoDateStart.isNotEmpty && 
              controller.eventInfoDateEnd.isNotEmpty) {
            dateText = '${controller.eventInfoDateStart} - ${controller.eventInfoDateEnd}';
          } else {
            dateText = '本周数据';
          }
          break;
          
        case TimeRange.month:
          // 月视图：显示月份
          if (controller.eventInfoDateStart.isNotEmpty) {
            dateText = controller.eventInfoDateStart;
          } else {
            final now = DateTime.now();
            dateText = '${now.year}年${now.month.toString().padLeft(2, '0')}月';
          }
          break;
      }
      
      return Text(
        dateText,
        style: TextStyle(fontSize: 14.sp, color: Colors.grey[400]),
      );
    });
  }



  /// 构建过去7天环状图视图
  Widget _buildWeeklyRingView() {
    return Obx(() {
      final weekData = _getLast7DaysData();

      if (weekData.isEmpty) {
      return Container(
        height: 200.h,
        child: Center(
          child: Text(
            '数据加载中...',
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.grey[500],
            ),
          ),
        ),
      );
    }

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border:
            Border.all(color: const Color.fromRGBO(33, 33, 33, 1), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '过去7天的目标达成情况',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 20.h),

          // 日期标签行
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: weekData.asMap().entries.map((entry) {
              final index = entry.key;
              final isSelected = controller.selectedDayIndex == index;
              
              // 优先使用 API 数据中的星期信息
              String dayName;
              if (controller.targetSituationData.isNotEmpty && 
                  index < controller.targetSituationData.length) {
                final apiWeek = controller.targetSituationData[index].week;
                dayName = apiWeek.replaceAll('周', ''); // "周一" -> "一"
              } else {
                final data = entry.value;
                final weekday = data.date.weekday;
                final dayNames = ['一', '二', '三', '四', '五', '六', '日'];
                dayName = dayNames[weekday - 1];
              }

              return Text(
                dayName,
                style: TextStyle(
                  fontSize: 12.sp,
                  color:
                      isSelected ? const Color(0xFFFFD700) : Colors.grey[400],
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
              );
            }).toList(),
          ),

          SizedBox(height: 12.h),

          // 环状图行
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: weekData.asMap().entries.map((entry) {
              final index = entry.key;
              final data = entry.value;
              final isSelected = controller.selectedDayIndex == index;

              return GestureDetector(
                onTap: () {
                  // 点击环形图切换选中状态
                  controller.fetchDataForSelectedDay(index, data.isToday);
                },
                child: Container(
                  width: 40.w,
                  height: 40.w,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      // 外环 - 步数
                      SizedBox(
                        width: 40.w,
                        height: 40.w,
                        child: CircularProgressIndicator(
                          value: data.stepsProgress,
                          strokeWidth: 4.w,
                          backgroundColor: const Color(0xFF5b5c5c),
                          valueColor: AlwaysStoppedAnimation<Color>(
                              isSelected || data.isStepsCompleted
                                  ? const Color(0xFFFFD700)
                                  : Colors.grey[600]!),
                          strokeCap: StrokeCap.round,
                        ),
                      ),
                      // 中环 - 卡路里
                      SizedBox(
                        width: 28.w,
                        height: 28.w,
                        child: CircularProgressIndicator(
                          value: data.caloriesProgress,
                          strokeWidth: 3.w,
                          backgroundColor: const Color(0xFF5b5c5c),
                          valueColor: AlwaysStoppedAnimation<Color>(
                              isSelected || data.isCaloriesCompleted
                                  ? const Color(0xFFFF6B35)
                                  : Colors.grey[600]!),
                          strokeCap: StrokeCap.round,
                        ),
                      ),
                      // 内环 - 时长
                      SizedBox(
                        width: 16.w,
                        height: 16.w,
                        child: CircularProgressIndicator(
                          value: data.timeProgress,
                          strokeWidth: 2.w,
                          backgroundColor: const Color(0xFF5b5c5c),
                          valueColor: AlwaysStoppedAnimation<Color>(
                              isSelected || data.isTimeCompleted
                                  ? const Color(0xFF00D4AA)
                                  : Colors.grey[600]!),
                          strokeCap: StrokeCap.round,
                        ),
                      ),
                    ],
                  ),
                ),
              );
            }).toList(),
          ),

          SizedBox(height: 16.h),

          // 选中日期的数据展示
          if (controller.selectedDayIndex < weekData.length)
            _buildSelectedDayInfo(weekData[controller.selectedDayIndex]),
        ],
      ),
    );
    });
  }

  /// 构建选中日期的信息展示
  Widget _buildSelectedDayInfo(DailyData selectedDay) {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        children: [
          // 居中显示的大环状图
          Center(
            child: SizedBox(
              width: 120.w,
              height: 120.w,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // 外环 - 步数
                  SizedBox(
                    width: 116.w,
                    height: 116.w,
                    child: CircularProgressIndicator(
                      value: selectedDay.stepsProgress,
                      strokeWidth: 12.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                          const Color(0xFFFFD700)),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                  // 中环 - 卡路里
                  SizedBox(
                    width: 84.w,
                    height: 84.w,
                    child: CircularProgressIndicator(
                      value: selectedDay.caloriesProgress,
                      strokeWidth: 12.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                          const Color(0xFFFF6B35)),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                  // 内环 - 时长
                  SizedBox(
                    width: 54.w,
                    height: 54.w,
                    child: CircularProgressIndicator(
                      value: selectedDay.timeProgress,
                      strokeWidth: 12.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                          const Color(0xFF00D4AA)),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: 20.h),

          // 选中日期的具体数据
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSelectedDayMetric('步数', '${selectedDay.steps}', '/8000',
                  const Color(0xFFFFD700)),
              _buildSelectedDayMetric(
                  '卡路里',
                  selectedDay.calories >= 100000
                      ? '${(selectedDay.calories / 10000).round()}'
                      : '${selectedDay.calories}',
                  '/400',
                  const Color(0xFFFF6B35)),
              _buildSelectedDayMetric('时长', '${selectedDay.time ?? 0}', '/30分钟',
                  const Color(0xFF00D4AA)),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建选中日期的指标显示
  Widget _buildSelectedDayMetric(
      String title, String value, String target, Color color) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[400],
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          value,
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        Text(
          target,
          style: TextStyle(
            fontSize: 10.sp,
            color: Colors.grey[500],
          ),
        ),
      ],
    );
  }

  /// 构建步数区间柱状图（固定显示今天的数据）
  Widget _buildStepsRangeBarChart() {
    return Obx(() {
      // 获取API数据
      final compareData = controller.compareDistanceData;
      final todaySteps = compareData?.steps ?? 0;

      // 定义步数区间
      final ranges = [
        {'min': 0, 'max': 3000, 'label': '0-3k'},
        {'min': 3001, 'max': 6000, 'label': '3k-6k'},
        {'min': 6001, 'max': 9000, 'label': '6k-9k'},
        {'min': 9001, 'max': 12000, 'label': '9k-12k'},
        {'min': 12001, 'max': 15000, 'label': '12k-15k'},
        {'min': 15001, 'max': 18000, 'label': '15k-18k'},
        {'min': 18001, 'max': double.infinity, 'label': '18k+'},
      ];

      // 找到当前步数所在的区间
      int currentRangeIndex = 0;
      for (int i = 0; i < ranges.length; i++) {
        final min = ranges[i]['min'] as int;
        final max = ranges[i]['max'] as int;
        if (todaySteps >= min && todaySteps <= max) {
          currentRangeIndex = i;
          break;
        }
      }

      return Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: const Color.fromRGBO(3, 0, 3, 1),
          borderRadius: BorderRadius.circular(20.r),
          border:
              Border.all(color: const Color.fromRGBO(33, 33, 33, 1), width: 1),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 4.h),
            Text(
              '与同龄${compareData?.sex ?? '女'}性用户对比',
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[400],
              ),
            ),
            SizedBox(height: 16.h),

            // 垂直柱状图
            Container(
              height: 160.h,
              child: Column(
                children: [
                  // 柱状图区域
                  Expanded(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: ranges.asMap().entries.map((entry) {
                        final index = entry.key;
                        final isCurrent = index == currentRangeIndex;

                        // 使用API返回的真实分布数据
                        final distribution =
                            compareData?.allValues ?? [35, 25, 20, 12, 5, 2, 1];
                        final value = distribution[index];
                        final maxValue =
                            distribution.reduce((a, b) => a > b ? a : b);

                        // 计算柱子高度，确保有明显的高度差异
                        final height = maxValue > 0
                            ? (value / maxValue * 80.h)
                                .clamp(8.h, 80.h)
                            : 8.h;

                        return Expanded(
                          child: Container(
                            margin: EdgeInsets.symmetric(horizontal: 2.w),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                // 柱子
                                Container(
                                  width: 10.w,
                                  height: height,
                                  decoration: BoxDecoration(
                                    color: isCurrent
                                        ? const Color(0xFFFFD700)
                                        : Colors.grey[600],
                                    borderRadius: BorderRadius.circular(4.r),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),

                  SizedBox(height: 4.h),

                  // 黄色基线
                  Container(
                    height: 2.h,
                    color: const Color(0xFFFFD700),
                  ),

                  SizedBox(height: 4.h),

                  // 区间标签
                  Row(
                    children: ranges.asMap().entries.map((entry) {
                      final index = entry.key;
                      final range = entry.value;
                      final isCurrent = index == currentRangeIndex;

                      return Expanded(
                        child: Column(
                          children: [
                            // 垂直刻度线
                            Container(
                              width: 1.w,
                              height: 6.h,
                              color: const Color(0xFFFFD700),
                            ),
                            SizedBox(height: 2.h),
                            // 区间范围标签
                            Text(
                              '${range['min']}',
                              style: TextStyle(
                                fontSize: 7.sp,
                                color: isCurrent
                                    ? const Color(0xFFFFD700)
                                    : Colors.grey[400],
                                fontWeight: isCurrent
                                    ? FontWeight.w600
                                    : FontWeight.normal,
                              ),
                            ),
                            Text(
                              '|',
                              style: TextStyle(
                                fontSize: 7.sp,
                                color: isCurrent
                                    ? const Color(0xFFFFD700)
                                    : Colors.grey[400],
                                fontWeight: isCurrent
                                    ? FontWeight.w600
                                    : FontWeight.normal,
                              ),
                            ),
                            Text(
                              index == ranges.length - 1
                                  ? '∞'
                                  : '${range['max']}',
                              style: TextStyle(
                                fontSize: 7.sp,
                                color: isCurrent
                                    ? const Color(0xFFFFD700)
                                    : Colors.grey[400],
                                fontWeight: isCurrent
                                    ? FontWeight.w600
                                    : FontWeight.normal,
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建步数显示
  Widget _buildStepsDisplay() {
    return Obx(() {
      // 根据时间范围显示不同的数据
      int displaySteps;
      String unitText;

      switch (controller.currentTimeRange) {
        case TimeRange.day:
          // 日视图：显示今天的步数
          if (controller.selectedTimeIndex != -1) {
            // 柱状图时段数据 - 优先使用API数据
            final hourlySteps = controller.eventInfoHourlySteps.isNotEmpty
                ? controller.eventInfoHourlySteps
                : (controller.ringController.stepsData?.hourlySteps
                        ?.map((e) => e ?? 0)
                        .toList() ??
                    []);
            displaySteps = (controller.selectedTimeIndex < hourlySteps.length)
                ? (hourlySteps[controller.selectedTimeIndex] ?? 0)
                : 0;
          } else {
            // 默认显示今天的总步数 - 优先使用API数据
            displaySteps = controller.eventInfoTotalSteps > 0
                ? controller.eventInfoTotalSteps
                : (controller.ringController.stepsData?.steps ?? 0);
          }
          unitText = '步';
          break;

        case TimeRange.week:
          // 周视图：显示本周平均步数
          final weekData = controller.targetSituationData;
          if (weekData.isNotEmpty) {
            final totalSteps =
                weekData.fold<int>(0, (sum, day) => sum + day.steps);
            displaySteps = (totalSteps / weekData.length).round();
          } else {
            displaySteps = 0;
          }
          unitText = '步/天';
          break;

        case TimeRange.month:
          // 月视图：显示本月平均步数
          final now = DateTime.now();
          final endOfMonth = DateTime(now.year, now.month + 1, 0);

          // 获取真实月度数据
          final monthlySteps = _getMonthlySteps(now);
          displaySteps = (monthlySteps / endOfMonth.day).round();

          unitText = '步/天';
          break;
      }

      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            '$displaySteps',
            style: TextStyle(
              fontSize: 64.sp,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(bottom: 8.h),
            child: Text(
              ' $unitText',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.grey[400],
              ),
            ),
          ),
        ],
      );
    });
  }

  /// 构建步数柱状图
  Widget _buildStepsChart() {
    return Obx(() {
      // 根据时间范围显示不同的图表数据
      List<int>? chartData;
      String chartTitle;
      List<String> xAxisLabels;
      int maxValue;

      switch (controller.currentTimeRange) {
        case TimeRange.day:
          // 日视图：显示今天的小时数据 - 优先使用API数据
          chartData = controller.eventInfoHourlySteps.isNotEmpty
              ? controller.eventInfoHourlySteps
              : (controller.detailedStepsData.isNotEmpty
                  ? controller.detailedStepsData
                  : (controller.ringController.stepsData?.hourlySteps
                          ?.map((e) => e ?? 0)
                          .toList() ??
                      []));
          chartTitle = '今日活动分布';

          if (chartData.isEmpty) {
            return Container(
              height: 120.h,
              child: Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (controller.isLoadingDetailedData) ...[
                      CircularProgressIndicator(
                        valueColor:
                            AlwaysStoppedAnimation<Color>(Colors.grey[400]!),
                        strokeWidth: 2.w,
                      ),
                      SizedBox(height: 8.h),
                      Text(
                        '正在获取详细数据...',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[500],
                        ),
                      ),
                    ] else ...[
                      Text(
                        '暂无详细数据',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[500],
                        ),
                      ),
                      SizedBox(height: 8.h),
                      Text(
                        '请等待数据同步...',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: Colors.grey[600],
                        ),
                      ),
                      SizedBox(height: 8.h),
                      ElevatedButton(
                        onPressed: controller.refreshDetailedData,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFFFFD700),
                          foregroundColor: Colors.black,
                          padding: EdgeInsets.symmetric(
                              horizontal: 16.w, vertical: 8.h),
                        ),
                        child: Text(
                          '刷新数据',
                          style: TextStyle(fontSize: 12.sp),
                        ),
                      ),
                    ],
                  ],
                ),
              ),
            );
          }

          maxValue = chartData.reduce((a, b) => a > b ? a : b);
          if (maxValue == 0) {
            return Container(
              height: 120.h,
              child: Center(
                child: Text(
                  '今日暂无活动',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.grey[500],
                  ),
                ),
              ),
            );
          }

          xAxisLabels = List.generate(7, (i) => '${i * 4}:00');
          break;

        case TimeRange.week:
          // 周视图：显示本周每天的数据 - 优先使用API数据
          final apiWeekData = controller.targetSituationData;
          if (apiWeekData.isNotEmpty) {
            chartData = apiWeekData.map((day) => day.steps).toList();
          } else {
            final weekData = _getCurrentWeekData();
            if (weekData.isEmpty) {
              return Container(
                height: 120.h,
                child: Center(
                  child: Text(
                    '暂无周数据',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey[500],
                    ),
                  ),
                ),
              );
            }
            chartData = weekData.map((day) => day.steps).toList();
          }

          chartTitle = '本周活动分布';
          maxValue = chartData.reduce((a, b) => a > b ? a : b);
          xAxisLabels = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
          break;

        case TimeRange.month:
          // 月视图：显示本月每天的数据
          final now = DateTime.now();
          final daysInMonth = DateTime(now.year, now.month + 1, 0).day;
          chartData = List.generate(daysInMonth, (index) {
            final day = index + 1;
            final dayDate = DateTime(now.year, now.month, day);
            if (dayDate.isBefore(DateTime.now()) ||
                dayDate.isAtSameMomentAs(DateTime.now())) {
              // 获取真实数据
              final allHistoryData = controller.ringService.allHistoryData;
              final historyData = allHistoryData.firstWhere(
                (data) =>
                    data.date.year == dayDate.year &&
                    data.date.month == dayDate.month &&
                    data.date.day == dayDate.day,
                orElse: () => DailyData(
                  date: dayDate,
                  steps: 0,
                  distance: 0,
                  calories: 0,
                  time: 0,
                  isToday: false,
                ),
              );
              return historyData.steps;
            }
            return 0;
          });

          chartTitle = '本月活动分布';
          maxValue = chartData.reduce((a, b) => a > b ? a : b);
          xAxisLabels = List.generate(daysInMonth, (i) => '${i + 1}');
          break;
      }

      return Container(
        height: 180.h,
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: const Color.fromRGBO(3, 0, 3, 1),
          borderRadius: BorderRadius.circular(20.r),
          border:
              Border.all(color: const Color.fromRGBO(33, 33, 33, 1), width: 1),
        ),
        child: Column(
          children: [
            // 图表标题
            Text(
              chartTitle,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
            SizedBox(height: 12.h),

            // Y轴标签和柱状图
            Expanded(
              child: Row(
                children: [
                  // Y轴标签
                  Container(
                    width: 30.w,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '${_formatYAxisLabel(maxValue)}',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                        Text(
                          '${_formatYAxisLabel((maxValue / 2).round())}',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                        Text(
                          '0',
                          style: TextStyle(
                            fontSize: 8.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                  ),

                  SizedBox(width: 8.w),

                  // 柱状图区域
                  Expanded(
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        final chartWidth = constraints.maxWidth;
                        final barWidth = chartWidth / chartData!.length;

                        return GestureDetector(
                          onPanUpdate: (details) {
                            controller.handleChartPanUpdate(
                                details.localPosition.dx,
                                barWidth,
                                chartData!.length);
                          },
                          onPanEnd: (details) {
                            controller.handleChartPanEnd();
                          },
                          onTapUp: (details) {
                            controller.handleChartTapUp(
                                details.localPosition.dx,
                                barWidth,
                                chartData!.length);
                          },
                          child: Container(
                            height: 120.h,
                            child: Stack(
                              children: [
                                // 柱状图
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.end,
                                  children:
                                      chartData.asMap().entries.map((entry) {
                                    final index = entry.key;
                                    final value = entry.value;
                                    // 确保柱子有最小高度，并且能够明显显示差异
                                    final height = value > 0
                                        ? (value / maxValue * 110.h).clamp(
                                            12.h, 110.h) // 最小高度12.h，最大110.h
                                        : 4.h; // 0值显示最小高度
                                    final isSelected = controller
                                                .currentTimeRange ==
                                            TimeRange.day &&
                                        controller.selectedTimeIndex == index;

                                    // 根据时间范围调整柱子宽度
                                    final barMargin =
                                        controller.currentTimeRange ==
                                                TimeRange.week
                                            ? 10.w
                                            : 0.5.w;
                                    final barWidthLocal =
                                        controller.currentTimeRange ==
                                                TimeRange.week
                                            ? 1.w
                                            : null;

                                    return Expanded(
                                      child: Container(
                                        margin: EdgeInsets.symmetric(
                                            horizontal: barMargin),
                                        child: Container(
                                          width: barWidthLocal,
                                          height: height,
                                          decoration: BoxDecoration(
                                            color: isSelected
                                                ? const Color(0xFFFF6B35)
                                                : (value > 0
                                                    ? const Color(0xFFFFD700)
                                                    : Colors.grey[800]),
                                            borderRadius:
                                                BorderRadius.circular(2.r),
                                          ),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ),

                                // 拖动指示线（仅日视图）
                                if (controller.currentTimeRange ==
                                        TimeRange.day &&
                                    controller.dragLineX != null)
                                  Positioned(
                                    left: controller.dragLineX! - 1.w,
                                    top: 0,
                                    bottom: 0,
                                    child: Container(
                                      width: 2.w,
                                      color: Colors.red,
                                    ),
                                  ),

                                // 选中指示线（仅日视图）
                                if (controller.currentTimeRange ==
                                        TimeRange.day &&
                                    controller.selectedTimeIndex != -1 &&
                                    controller.dragLineX == null)
                                  Positioned(
                                    left: (controller.selectedTimeIndex + 0.5) *
                                            barWidth -
                                        1.w,
                                    top: 0,
                                    bottom: 0,
                                    child: Container(
                                      width: 2.w,
                                      color: const Color(0xFFFF6B35),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),

            SizedBox(height: 8.h),

            // X轴标签
            Row(
              children: [
                SizedBox(width: 38.w), // 对齐Y轴标签的宽度
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: xAxisLabels
                        .map((label) => Text(
                              label,
                              style: TextStyle(
                                fontSize: 8.sp,
                                color: Colors.grey[400],
                              ),
                            ))
                        .toList(),
                  ),
                ),
              ],
            ),

            SizedBox(height: 8.h),

            // 使用提示
            Container(
              padding: EdgeInsets.symmetric(vertical: 4.h, horizontal: 8.w),
              decoration: BoxDecoration(
                color: (controller.currentTimeRange == TimeRange.day &&
                        controller.selectedTimeIndex != -1)
                    ? const Color(0xFFFF6B35)
                    : Colors.grey[800],
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Text(
                controller.currentTimeRange == TimeRange.day
                    ? (controller.selectedTimeIndex != -1
                        ? '拖动红线或点击柱子查看时段数据'
                        : '拖动或点击图表查看具体时段数据')
                    : '${chartTitle}数据展示',
                style: TextStyle(
                  fontSize: 10.sp,
                  color: Colors.white,
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  // 以下是辅助方法，从原来的页面中提取
  /// 获取最近7天的数据（按星期几排列，今天在最后）
  List<DailyData> _getLast7DaysData() {
    // 优先使用API数据
    final apiData = controller.targetSituationData;
    if (apiData.isNotEmpty) {
      return apiData
          .map((item) => DailyData(
                date: item.date,
                steps: item.steps,
                distance: 0, // API未提供
                calories: item.calorie,
                time: item.duration,
                isToday: item.date.year == DateTime.now().year &&
                    item.date.month == DateTime.now().month &&
                    item.date.day == DateTime.now().day,
              ))
          .toList();
    }

    // 降级使用本地数据
    final now = DateTime.now();
    final allHistoryData = controller.ringService.allHistoryData;
    final weekData = <DailyData>[];

    // 生成最近7天的数据，按星期几排列
    for (int i = 0; i < 7; i++) {
      // 计算要获取的日期
      // 从6天前开始，到今天结束
      final date = now.subtract(Duration(days: 6 - i));

      // 查找对应的历史数据
      final historyData = allHistoryData.firstWhere(
        (data) =>
            data.date.year == date.year &&
            data.date.month == date.month &&
            data.date.day == date.day,
        orElse: () => DailyData(
          date: date,
          steps: 0,
          distance: 0,
          calories: 0,
          time: 0,
          isToday: i == 6, // 最后一个位置是今天
        ),
      );

      weekData.add(historyData);
    }

    return weekData;
  }

  /// 获取当前周的数据（上周日到本周六）
  List<DailyData> _getCurrentWeekData() {
    final now = DateTime.now();
    final today = now.weekday; // 1=周一，7=周日

    // 计算上周日的日期
    final daysToLastSunday = today == 7 ? 0 : today;
    final lastSunday = now.subtract(Duration(days: daysToLastSunday));

    // 从RingService获取数据
    final allHistoryData = controller.ringService.allHistoryData;
    final weekData = <DailyData>[];

    // 生成上周日到本周六的数据
    for (int i = 0; i < 7; i++) {
      final date = lastSunday.add(Duration(days: i));

      // 查找对应的历史数据
      final historyData = allHistoryData.firstWhere(
        (data) {
          final isMatch = data.date.year == date.year &&
              data.date.month == date.month &&
              data.date.day == date.day;
          return isMatch;
        },
        orElse: () {
          return DailyData(
            date: date,
            steps: 0,
            distance: 0,
            calories: 0,
            time: 0,
            isToday: date.year == now.year &&
                date.month == now.month &&
                date.day == now.day,
          );
        },
      );

      weekData.add(historyData);
    }

    return weekData;
  }

  /// 获取月度步数数据（真实数据）
  int _getMonthlySteps(DateTime date) {
    final daysInMonth = DateTime(date.year, date.month + 1, 0).day;
    int totalSteps = 0;

    // 从RingService获取真实数据
    final allHistoryData = controller.ringService.allHistoryData;

    for (int day = 1; day <= daysInMonth; day++) {
      final dayDate = DateTime(date.year, date.month, day);
      if (dayDate.isBefore(DateTime.now()) ||
          dayDate.isAtSameMomentAs(DateTime.now())) {
        // 查找对应的历史数据
        final historyData = allHistoryData.firstWhere(
          (data) =>
              data.date.year == dayDate.year &&
              data.date.month == dayDate.month &&
              data.date.day == dayDate.day,
          orElse: () => DailyData(
            date: dayDate,
            steps: 0,
            distance: 0,
            calories: 0,
            time: 0,
            isToday: false,
          ),
        );
        totalSteps += historyData.steps;
      }
    }

    return totalSteps;
  }

  /// 格式化Y轴标签
  String _formatYAxisLabel(int value) {
    if (value >= 10000) {
      return '${(value / 1000).toStringAsFixed(1)}k';
    } else if (value >= 1000) {
      return '${(value / 1000).toStringAsFixed(1)}k';
    } else {
      return value.toString();
    }
  }
}
